package com.edu.tool.util;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @FileName：IpUtil.java
 * @Description：@TODO
 * @Author：thy
 * @CreateTime：下午4:57:09
 */
public class IpUtil {
	private static Logger log = Logger.getLogger(IpUtil.class);

	private static String localIp = null;
	
    private static String OS_NAME = null;
	
    static {
    	log.info("初始化获取系统名称...");
        OS_NAME = System.getProperty("os.name");
    }

	/**
	 * 获取当前网络ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		log.info("X-Real-IP:"+request.getHeader("X-Real-IP")+"x-forwarded-for:"+request.getHeader("x-forwarded-for")+" X-Forwarded-For:"+request.getHeader("X-Forwarded-For"));
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	public static String getLocalIpAddr() {
		if (localIp == null) {
			try {
				// 查询内网IP
	            switch (IpUtil.getOsType()) {
	            case 1:
	                IpUtil.getWinInnerIP();
	                break;
	            case 2:
	                localIp="";//IpUtil.getLinuxIP(2);
	                break;
	            default:
	                break;
	            }
			} catch (Exception e) {
				log.error("获取本机IP异常", e);
			}
		}
		return localIp;
	}
	
	/**
     * 获取window平台下内网IP
     * 
     * @return IP
     */
    private static String getWinInnerIP() {
        InetAddress[] inetAdds;
        try {
            inetAdds = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            log.error("getWinInnerIP exception", e);
            return localIp;
        }
        return localIp = inetAdds[0].getHostAddress();
    }

    /**
     * 获取linux下的IP
     * @param queryFlag
     * 1表示查询外网IP 2表示查询内网IP
     * @return IP
     * @throws IOException
     */
    private static String getLinuxIP(int queryFlag) {
         LineNumberReader input = null;
         String pathString = IpUtil.class.getResource("/").getPath();
         //类的路径
         Process process=null;
         String line = "";
         try {
            Runtime.getRuntime().exec("dos2unix "+pathString+"test.sh");
            process = Runtime.getRuntime().exec("sh "+pathString+"test.sh "+(queryFlag==1?"1":"2"));
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            input = new LineNumberReader(ir);
            if((line = input.readLine()) != null) {
            	localIp = line;
            }
         } catch (IOException e) {
            log.error("linux下获取IP失败!", e);
        }
        return localIp;
    }
	
	/**
     * 目前只支持window和linux两种平台
     * 
     * @return 1 window 2 linux -1:未知
     */
    public static int getOsType() {
        // 将获取到的系统类型名称转为全部小写
        OS_NAME = OS_NAME.toLowerCase();
        if (OS_NAME.startsWith("win")) {
            return 1;
        }
        if (OS_NAME.startsWith("linux")) {
            return 2;
        }
        return -1;
    }
    
    public static void main(String[] args) throws IOException {
        log.info("操作系统为："+ IpUtil.getOsType());
        log.info("内网IP为："+ IpUtil.getLocalIpAddr());
    }

}
